
/**
 * Date:2019年5月30日下午4:47:28
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.client.core;

import java.util.concurrent.TimeUnit;

import com.xue.im.client.handler.HeartBeatRequestHandler;
import com.xue.im.client.handler.LoginAuthRequestHandler;
import com.xue.im.client.handler.TextRequestHandler;
import com.xue.im.common.IMUtil;
import com.xue.im.common.coder.MessageDecoder;
import com.xue.im.common.coder.MessageEncoder;
import com.xue.im.common.vo.Message;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;

/**
 * Description: 客户端 <br/>
 * Date: 2019年5月30日 下午4:47:28 <br/>
 * 
 * @author xuejianxin
 */
public class IMClient {
	private final String host;
	private final int port;
	private Channel messageChannel;

	private EventLoopGroup group = new NioEventLoopGroup();

	public IMClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void connect() throws Exception {

		try {

			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					//.handler(new LoggingHandler(LogLevel.INFO))
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast("decoder", new MessageDecoder(IMUtil.MESSAGE_LEN, 4, 4));
							ch.pipeline().addLast("encoder", new MessageEncoder());
							ch.pipeline().addLast("readTimeout", new ReadTimeoutHandler(50));
							ch.pipeline().addLast("login", new LoginAuthRequestHandler());
							ch.pipeline().addLast("heartBeat", new HeartBeatRequestHandler());
							ch.pipeline().addLast("text", new TextRequestHandler());
						}
					});
			final ChannelFuture f = b.connect(host, port).sync();

			f.addListener(new ChannelFutureListener() {
				public void operationComplete(ChannelFuture cf) throws Exception {
					if (f.isSuccess()) {
						System.out.println("连接服务器成功");
						messageChannel = cf.channel();

					} else {
						System.out.println("连接服务器失败");
					}
				}
			});

			f.channel().closeFuture().sync();
		} finally {
			// 所有资源释放完成后，清空资源，再次发起重连请求
			submit(() -> {
				try {
					TimeUnit.SECONDS.sleep(5);
					connect();// 重连
				} catch (Exception e) {
					// e.printStackTrace();
				}
			});
		}

	}

	public void shutdown() {
		if (!group.isShutdown()) {
			group.shutdownGracefully();
		}
	}

	public void submit(Runnable task) {
		group.execute(task);
	}

	public void sendMessage(Message msg) {
		this.messageChannel.writeAndFlush(msg);
	}

	public static void main(String[] args) {
		try {
			new IMClient("localhost", 9098).connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
